﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Globalization;
using System.Text.RegularExpressions;

namespace WeiboAutomation
{
    public partial class frmWeibo : Form
    {
        #region 微博列表模板
        const string htmlPattern = @"<!DOCTYPE html>
<html lang=""en"" xmlns=""http://www.w3.org/1999/xhtml"">
<head>
	<title></title>
	<style type=""text/css"">
		html, body {
			font-size: 12px;
			cursor: default;
			padding: 5px;
			margin: 0;
			font-family:宋体,Tahoma;
		}

		div.status {
			padding-left: 0px;
			position: relative;
			margin-bottom: 0px;
			min-height:80px;
			_height:80px;
		}

			div.status p {
				margin: 0 0 5px 0;
				line-height: 1.2;
				padding: 0;
			}

				div.status p span.name {
					color: #369;
				}
				div.status p.status-content {
					color: #333;
				}
				div.status p.status-count {
					color:#999;
				}
				div.status p.status-source {
					color:#999;
				}

			div.status .face {
				position: absolute;
				left: 0;
				top: 0;
			}

			div.status div.repost {
				border: solid 1px #ACD;
				background: #F0FAFF;
				padding: 10px 10px 0 10px;
			}

		div.repost p.repost-content {
			color: #666 !important;
		}
	</style>
</head>
<body>
<!--StatusesList-->
</body>
</html>";
        const string imageParttern = @"<img src=""{0}"" alt=""图片"" class=""inner-pic"" />";
//        const string statusPattern = @"	<div class=""status"">
//		<hr/>
//		<p class=""status-content""><span class=""name"">{1}</span>：{2}</p>
//		{3}
//		<p class=""status-count"">转发[{4}] 评论[{5}]</p>
//        <p class=""status-source"">{6} 来自{7}</p>
//	</div>
//";
        const string statusPattern = @"	<div class=""status"">
		<hr/>
		<p class=""status-content""><span class=""name"">{1}</span>：{2}</p>
		{3}
        <p class=""status-source"">{6} 来自{7}</p>
	</div>
";
//        const string repostPattern = @"	<div class=""status"">
//		<hr/>
//		<p class=""status-content""><span class=""name"">{1}</span>：{2}</p>
//		<div class=""repost"">
//			<p class=""repost-cotent""><span class=""name"">@{3}</span>：{4}</p>
//			{5}
//			<p class=""status-count"">转发[{6}] 评论[{7}]</p>
//		</div>
//		<p class=""status-count"">转发[{8}] 评论[{9}]</p>
//        <p class=""status-source"">{10} 来自{11}</p>
//	</div>
//";
        const string repostPattern = @"	<div class=""status"">
		<hr/>
		<p class=""status-content""><span class=""name"">{1}</span>：{2}</p>
		<div class=""repost"">
			<p class=""repost-cotent""><span class=""name"">@{3}</span>：{4}</p>
			{5}
		</div>
        <p class=""status-source"">{10} 来自{11}</p>
	</div>
";
        #endregion

        private NetDimension.Weibo.OAuth oauth;
        private NetDimension.Weibo.Client Sina;
        private string UserID = string.Empty;

        Logger logger = new Logger();

        XML xml = new XML();
        public string Account = "";
        public string Password = "";

        public frmWeibo(NetDimension.Weibo.OAuth oauth)
        {
            InitializeComponent();
            this.oauth = oauth;
            Sina = new NetDimension.Weibo.Client(oauth);

            Account = xml.read("Account");
            Password = xml.read("Password");
        }

        private void frmWeibo_Load(object sender, EventArgs e)
        {
            LoadUserInformation();
            LoadFriendTimeline();
        }

        private void LoadUserInformation()
        {
            Thread thUserInfo = new Thread(new ThreadStart(delegate()
            {
                string userID = Sina.API.Entity.Account.GetUID();
                NetDimension.Weibo.Entities.user.Entity userInfo = Sina.API.Entity.Users.Show(userID);
                this.UIInvoke(() =>
                {
                    lblScreenName.Text = userInfo.ScreenName;
                    lblLocation.Text = userInfo.Gender.ToUpper() + " " + userInfo.Location;
                    imgProfile.ImageLocation = userInfo.ProfileImageUrl;
                    lblUserStatus.Text = string.Format("关注{0} 粉丝{1} 微博{2} 收藏{3}", userInfo.FriendsCount, userInfo.FollowersCount, userInfo.StatusesCount, userInfo.FavouritesCount);
                });
            }));

            thUserInfo.IsBackground = true;
            thUserInfo.Start();
        }
        private void LoadFriendTimeline()
        {
            Thread thLoad = new Thread(new ThreadStart(delegate()
            {
                StringBuilder statusBuilder = new StringBuilder();
                var json = Sina.API.Entity.Statuses.FriendsTimeline(count: 10);
                if (json.Statuses != null)
                {
                    foreach (var status in json.Statuses)
                    {
                        if (status.User == null)
                            continue;

                        Regex.Matches(status.Source, "<a.+?>(.+?)</a>", RegexOptions.IgnoreCase);

                        if (status.RetweetedStatus != null && status.RetweetedStatus.User != null)
                        {
                            statusBuilder.AppendFormat(repostPattern,
                                status.User.ProfileImageUrl,
                                status.User.ScreenName,
                                status.Text,
                                status.RetweetedStatus.User.ScreenName,
                                status.RetweetedStatus.Text,
                                string.IsNullOrEmpty(status.RetweetedStatus.ThumbnailPictureUrl) ? "" :
                                string.Format(imageParttern, status.RetweetedStatus.ThumbnailPictureUrl),
                                status.RetweetedStatus.RepostsCount,
                                status.RetweetedStatus.CommentsCount,
                                status.RepostsCount, 
                                status.CommentsCount,
                                ConvertTimeFormat(status.CreatedAt),
                                status.Source.Substring(status.Source.IndexOf("\">") + ("\">").Length, status.Source.IndexOf("</a>") - status.Source.IndexOf("\">") - ("\">").Length));
                        }
                        else
                        {
                            statusBuilder.AppendFormat(statusPattern,
                                status.User.ProfileImageUrl,
                                status.User.ScreenName,
                                status.Text,
                                string.IsNullOrEmpty(status.ThumbnailPictureUrl) ? "" :
                                string.Format(imageParttern, status.ThumbnailPictureUrl),
                                status.RepostsCount, status.CommentsCount,
                                ConvertTimeFormat(status.CreatedAt),
                                status.Source.Substring(status.Source.IndexOf("\">") + ("\">").Length, status.Source.IndexOf("</a>") - status.Source.IndexOf("\">") - ("\">").Length));
                        }
                    }
                }

                var html = htmlPattern.Replace("<!--StatusesList-->", statusBuilder.ToString());
                this.UIInvoke(() =>
                {
                    wbStatuses.DocumentText = html;
                });
            }));
            thLoad.IsBackground = true;
            thLoad.Start();

        }

        private string ConvertTimeFormat(string time)
        {
            //string time = "Thu Dec 06 11:10:17 +0800 2012";
            CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture("en-US");
            string format = "ddd MMM dd HH:mm:ss zz00 yyyy";
            DateTime dt = DateTime.ParseExact(time, format, cultureInfo);
            string datex = dt.Month.ToString() + "月" + dt.Day.ToString() + "日" + " " + string.Format("{0:T}", dt);
            // dt.Hour.ToString() + ":" + dt.Minute.ToString() + ":" + dt.Second.ToString();
            return datex;
        }
    }
}
